import { useMessage } from '@/hooks'
import { api, useAxiosResponse } from '@/api'
import { useComInfoStoreWithOut } from '../../index'

import type {
  SysAppInfoOutupu,
  SysCustomComInfoOutupu,
  SysCustomComRenderOutupu,
} from './model'

const { notification } = useMessage()

/** 获取组件基础信息 */
export function getAppInfo(appId: string) {
  return new Promise<Nullable<SysAppInfoOutupu>>((resolve, reject) => {
    api
      .apiSysAppGetInfoPost({ appId })
      .then((res) => {
        const comStore = useComInfoStoreWithOut()
        const resData = useAxiosResponse<SysAppInfoOutupu>(res)

        comStore.setAppInfo(resData ?? null)
        resolve(resData ?? null)
      })
      .catch((error) => {
        notification.error({ message: '获取组件信息失败，请检查！' })
        reject(error)
      })
  })
}

/** 获取组件基础信息 */
export function getComInfo(appId: string, pageId: string) {
  return new Promise<Nullable<SysCustomComInfoOutupu>>((resolve, reject) => {
    api
      .apiSysAppPageGetInfoPost({
        appId,
        pageId,
      })
      .then((res) => {
        const comStore = useComInfoStoreWithOut()
        const resData = useAxiosResponse<SysCustomComInfoOutupu>(res)

        comStore.setComInfo(resData ?? null)
        resolve(resData ?? null)
      })
      .catch((error) => {
        notification.error({ message: '获取组件信息失败，请检查！' })
        reject(error)
      })
  })
}

/** 获取组件渲染信息 */
export function getComRenderInfo(appId: string, pageId: string) {
  return new Promise<Nullable<SysCustomComRenderOutupu>>((resolve, reject) => {
    api
      .apiSysAppPageGetRenderPost({
        appId,
        pageId,
      })
      .then((res) => {
        const comStore = useComInfoStoreWithOut()
        const resData = useAxiosResponse<SysCustomComRenderOutupu>(res)

        comStore.setComRenderInfo(resData ?? null)
        resolve(resData ?? null)
      })
      .catch((error) => {
        notification.error({ message: '获取组件渲染信息失败，请检查！' })
        reject(error)
      })
  })
}
